package com.hunterai.util;

import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.util.ByteSource;

/**
 * Utility class for password operations
 */
public class PasswordUtil {
    private static final int HASH_ITERATIONS = 1024;
    private static final RandomNumberGenerator random = new SecureRandomNumberGenerator();

    /**
     * Encrypts a password with a generated salt
     *
     * @param plainPassword the plain text password
     * @return the encrypted password
     */
    public static String encryptPassword(String plainPassword) {
        ByteSource salt = random.nextBytes();
        String hashedPasswordBase64 = new Sha256Hash(plainPassword, salt, HASH_ITERATIONS).toBase64();
        return salt.toBase64() + ":" + hashedPasswordBase64;
    }

    /**
     * Verifies if the provided plain password matches the stored hashed password
     *
     * @param plainPassword the plain text password to check
     * @param storedPassword the stored password hash
     * @return true if the password matches, false otherwise
     */
    public static boolean verifyPassword(String plainPassword, String storedPassword) {
        try {
            String[] parts = storedPassword.split(":");
            if (parts.length != 2) {
                return false;
            }

            String storedSaltBase64 = parts[0];
            String storedHashBase64 = parts[1];
            
            ByteSource salt = ByteSource.Util.bytes(org.apache.shiro.codec.Base64.decode(storedSaltBase64));
            String hashedPassword = new Sha256Hash(plainPassword, salt, HASH_ITERATIONS).toBase64();
            
            return hashedPassword.equals(storedHashBase64);
        } catch (Exception e) {
            return false;
        }
    }
} 